from django.shortcuts import render,HttpResponse,redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.hashers import make_password,check_password
from .models import *
#单个添加
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.core.mail import send_mail
# Create your views here.
from md import settings
from utils.comm import get_ali_object
import time
from elasticsearch import Elasticsearch
class Test(APIView):
    # permission_classes = (IsAuthenticated, )
    # # 标记需要进行jwt验证
    # authentication_classes = (JSONWebTokenAuthentication, ) 

    def get(self,request):
        # user = Users.objects.filter(id=2).first()
        # goods = Goods.objects.filter(id=1).first()
        # goods.user.add(user)
        # tt = ShowUserSer(user)
        # es = Elasticsearch(hosts=[{"host":'localhost', "port": 9200}])
        # result = es.indices.create(index='article', ignore=400)
        # print(result)
        return Response({'tt':''})
        # alipay = get_ali_object()

        # # 生成支付的url
        # query_params = alipay.direct_pay(
        #     subject="test",  # 商品简单描述
        #     out_trade_no="myorder" + str(time.time()),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        #     total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
        # )
        # pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        # return redirect(pay_url)

        # list=[{'name':'分类1','son':[{'name':'分类11','son':[{'name':'分类111'}]}]},{'name':'分类2','son':[{'name':'分类22','son':[{'name':'分类222'}]}]}]

        # list2=[{'name':'分类1','two':[{'name':'分类11'}],'three':[{'name':'分类111'}],'goods':[{'name':'商品'}]}]

        # msg='欢迎使用美多，如果想绑定邮箱<a href="http://localhost:8080/#/login" target="_blank">点击此处</a>'
        # result = send_mail('欢迎绑定邮箱','绑定邮箱',settings.EMAIL_HOST_USER, ['jiyuntest@163.com',
        # '763005825@qq.com'], html_message=msg)
        return Response({'mes':'list','list2':'list2'})
        


from .ser import *
import re
class Register(APIView):
    def post(self,request):
        #获取用户名
        username = request.data.get('username')
        #判断用户名是否为空、是否符合5-20们标准
        nameflag = re.match('\w{5,20}$',username)
        if not nameflag:
            return Response({'code':10010})
        #去users表中查找用户名是否存在
        user = Users.objects.filter(username=username).first()
        if user:
            #假如存在，提示已经存在不能注册
            return Response({'code':10011})

        #密码判断
        password = str(request.data.get('password'))
        passflag = re.match('\w{8,20}$',password)
        if not passflag:
            return Response({'code':10012})
        repassword = request.data.get('repassword')
        #判断两次输入是否一样
        if password != repassword:
            return Response({'code':10013})
        #手机号的判断
        mobile = request.data.get('mobile')
        mreg = re.match('^1[3,8][0-9]{9}$',mobile)
        if not mreg:
            return Response({'code':10014})
        #手机号是否重复
        #去users表中查找用户名是否存在
        user = Users.objects.filter(mobile=mobile).first()
        if user:
            #假如存在，提示已经存在不能注册
            return Response({'code':10015})
        #是否同意协议
        agree = request.data.get('agree')
        if agree == False:
            return Response({'code':10016})
        
        #注册，添加到users表
        request.data['password'] = make_password(request.data.get('password'))
        print(request.data)
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
             #假如不存在，提示可以注册
            return Response({'code':200})
        else:
            print(ser.errors)
             #假如不存在，提示可以注册
            return Response({'code':400})
       
from utils.captcha.captcha import captcha 
from utils.comm import get_redis_conn,send_message
     
#生成验证码图片
class ImageCode(APIView):
    def get(self,request):
        uuid = request.GET.get('uuid')
        name,text,image = captcha.generate_captcha()
        conn = get_redis_conn()
        conn.setex(uuid,300,text) 
        return HttpResponse(image,content_type='image/jpg')

#发送短信验证码
import random
class SendMes(APIView):
    def get(self,request):
        #接收客户端发送的数据
        imagecode = request.GET.get('imagecode')
        mobile = request.GET.get('mobile')
        uuid = request.GET.get('uuid')
        if not all([imagecode,mobile]):
            return Response({'code':10017})
        #验证图片验证码
        conn = get_redis_conn()
        #redis中取验证码
        code = conn.get(uuid)
       
        if code:
            code = str(code,encoding='utf8')
            #图片验证码对比
            if imagecode.lower() == code.lower():
                #验证通过后调用发送短信接口
                sms_code = random.randint(10000,99999)
                result = send_message(mobile,sms_code,1)
                #假如短信验证码发送成功
                if result:
                    #redis存短信验证码
                    conn.setex(mobile,60,sms_code)
                    #把图片验证码从redis删除
                    conn.delete(uuid)
                    return Response({'code':200})
                else:
                    return Response({'code':10020})
            else:
                return Response({'code':10019})
        else:
            return Response({'code':10018})

from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from rest_framework_jwt.views import obtain_jwt_token

class Login(APIView):
    permission_classes = (AllowAny, )
    # 标记需要进行jwt验证
    authentication_classes = (JSONWebTokenAuthentication, ) 
    def post(self,request):
        #获取用户输入
        username = request.data.get('username')
        password = request.data.get('password')
        #正则验证是否为手机号
        reg = re.match('^1[3,8][0-9]{9}$',username)
        if reg:
            #查询用户是否存在
            users = Users.objects.filter(mobile=username).first()
        else:
            #查询用户是否存在
            users = Users.objects.filter(username=username).first()
        #如果存在验证密码
        if users:
            if check_password(password,users.password):
                #构造token,返回
                payload = jwt_payload_handler(users)
                token = jwt_encode_handler(payload)
                return Response({'token':token,'name':users.username,'id':users.id,'mobile':users.mobile})
            else:
                return Response({"code":10030})
        else:
            return Response({"code":10020})
        #不存在返回没有此用户

class BindEmail(APIView):
    def post(self,request):
        #获取邮箱地址
        email = request.data.get('email')
        userid = request.data.get('userid')
       
        msg = '欢迎系统，请点击以下<a href="http://localhost:8000/users/callBackEmail/?userid='+userid+'">链接</a>'

        #发邮箱
        result = send_mail('绑定邮箱操作','',settings.EMAIL_HOST_USER,[email,],html_message=msg)
        #判断是否成功
        if result:
            #把userid,email存在redis
            conn = get_redis_conn()
            conn.setex(userid,1800,email)
            return Response({'code':200})
        return Response({'code':40010})

#绑定邮箱回调接口
class CallBackEmail(APIView):
    def get(self,request):
        userid = request.GET.get('userid')
        #非空验证
        if not userid:
            return Response({"code":40011})
        #通过userid去redis取email
        conn = get_redis_conn()
        email = conn.get(userid)
        #如果取到了email，去数据库查邮箱是否存在
        if email:
            email = str(email,encoding='utf8')
            #假如存在返回结果
            user = Users.objects.filter(email=email).first()
            if user:
                return Response({"code":40013})
            else:
                #根据userid更新用户邮箱
                Users.objects.filter(id=userid).update(email=email)
                #redis清除
                conn.delete(userid)
                #跳转邮箱绑定页面
                return redirect('http://localhost:8080/#/userInfo/?email='+email)
        else:
            return Response({"code":40012})


class GetArea(APIView):
    def get(self,request):
        #获取参数
        area_id = request.GET.get('area_id')
        #判断参数，假如没获取，取省的信息 parent=null
        if not area_id:
            areas = Area.objects.filter(parent__isnull=True).all()
        #如果有参数，通过参数获取他下面所有的市，或者区
        else:
            area = Area.objects.filter(id=area_id).first()
            areas = area.son
        #返回结果
        ser = AreaSer(areas,many=True)
        return Response({"code":200,'arealist':ser.data})

def returnCate(cates):
    # 1  分类1  null
    # 2  分类2  1
    # 3
    #定义返回的列表
    list=[]
    #定义字典
    dict={}
    #遍历cates,把cates组装成一个字典，格式为{'1':i,'2':i,'3':i}
    for i in cates:
        dict[i['id']]=i

	#遍历cates,for i in cates
    for i in cates:
        #判断i有没有父类
        if not i['parent']:
            #没有父类他为一级，直接加到list
            list.append(i)
        else:
            parent_id = i['parent']
            #有父类，判断这个父类下有没有子类
            if 'son' not in dict[parent_id]:
                #假如没有定义父类的子类列表  dict[i['parent']]['son']=[]
                dict[parent_id]['son']=[]
            #把子类append到子类中
            dict[parent_id]['son'].append(i)
    return list
#获取首页中所需要的分类及商品
def getGoodslist():
    #获取一级分类
    cates = Category.objects.filter(parent__isnull=True).all()
    list=[]
    
    for i in cates:
        dict={}
        dict['id']=i.id
        dict['name']=i.name 
        # dict['image']=i.pic
        # 获取一级下的所有二级
        two = Category.objects.filter(parent_id=i.id,level=2).all()
        twoSer = CategorySer(two,many=True)
        dict['two']=twoSer.data
        #获取一级下的所有三级
        three = Category.objects.filter(top_parent=i.id,level=3).all()
        threeSer = CategorySer(three,many=True)
        dict['three']=threeSer.data
        #获取一级下的所有商品
        goods = Goods.objects.filter(category1_id=i.id).all()
        goodsSer =GoodsSer(goods,many=True)
        dict['goods'] = goodsSer.data
        list.append(dict)
    return list

#首页接口
class Home(APIView):
    def get(self,request):
        #左边三级分类
        #获取到所有的分类信息
        cates = Category.objects.all()
        cdata = CategorySer(cates,many=True)
        catelist = returnCate(cdata.data)
        #焦点图
        adlist = Advert.objects.filter(type=1).all()
        adlist=AdvertSer(adlist,many=True)
        #新闻
        newslist=[]
        #广告图
        ad={}
        #三级分类带商品
        goodslist= getGoodslist()
        # 
        return Response({'code':200,'adlist':adlist.data,'catelist':catelist,'newslist':newslist,'ad':ad,'goodslist':goodslist})
        
from django.core.paginator import Paginator

class GetGoodsList(APIView):
    def get(self,request):
        #获取分类id
        cateid = request.GET.get('cateid')
        #查询此分类下的热销商品
        hotg = Goods.objects.filter(category_id=cateid).all().order_by('-sales')[:2]
        hotser = GoodsSer(hotg,many=True)
        #查找此分类下的商品
        #获取排序的类别
        type = request.GET.get('type')
        goods = Goods.objects.filter(category_id=cateid).all().order_by('-'+type)
        #分页  每页显示多少条，当前页面，一共有多少条
        #每页显示多少条
        page_size=1
        #当前页面
        page = request.GET.get('page')
        pag = Paginator(goods,page_size)
        #获取当前数据
        pgoods = pag.page(page)
        pgoodsSer = GoodsSer(pgoods,many=True)
        #对商品进行序列化返回
        return Response({'code':200,'hot':hotser.data,'goods':pgoodsSer.data,'tpages':pag.num_pages})
       
from django.core.paginator import Paginator
import json
class GetGoodsByCate(APIView):
    def get(self,request):
        #获取分类
        cateid = request.GET.get('cateid')
        #获取当前页
        cpage = request.GET.get('cpage')
        #获取排序字段
        type = request.GET.get('type')

        if type not in ['id','price','sales']:
            type='id'
        #获取此分类下的商品
        if cateid:
            goods = Goods.objects.filter(category_id=cateid).all().order_by('-'+type)
        else:
            goods = Goods.objects.all()
        #分页处理
        #每页显示多少条
        page_size = 1
        pag = Paginator(goods,page_size)
        #一共有多少页面
        tpages = pag.num_pages
        #获取当前页数据
        cgoods = pag.page(cpage)
        #序列化
        ser = GoodsSer(cgoods,many=True)
        #先从redis取，如果有直接返回，如果没有数据库
        conn = get_redis_conn()
        hot = conn.get('hotGoods')
        if hot:
            hotdata = json.loads(hot)
            print('!!!!!!')
        else:
            print('$$$$$$$$$$')
            #查询此分类下的热销商品
            hotg = Goods.objects.filter(category_id=cateid).all().order_by('-sales')[:2]
            hotser = GoodsSer(hotg,many=True)
            hotdata = hotser.data
            conn.set('hotGoods',json.dumps(hotdata))
        # 返回
        return Response({'code':200,'goods':ser.data,'tpages':tpages,'hot':hotdata})

from md.settings import MEDIA_URL
class CartManage(APIView):
    def post(self,request):
        #获取userid ,goodsid
        userid = request.data.get('userid')
        goodsid = request.data.get('goodsid')
        #去redis查此用户是否购买过此商品
        conn = get_redis_conn()
        key = 'cart_%userid'%int(userid)
        count = conn.hget(key,goodsid)
        #购买过数量加1
        if count:
            conn.hincrby(key,goodsid)
        else:
            #没买过添加
            conn.hset(key,goodsid,1)
        #返回结果
        return Response({'code':200})
    def get(self,request):
        #获取uerid
        userid = int(request.GET.get('userid'))
        #从redis中获取数据
        conn = get_redis_conn()
        key = 'cart_%userid'%int(userid)
        cart = conn.hgetall(key)
        #商品总个数
        total=0
        #商品列表
        cartlist=[]
        #选中列表
        slist=[]
        #选中商品总价格
        selectedtmoney=0
        #选中商品数量
        selectedtcount=0
        #是否全选
        selectedall = True

        #获取选中列表
        #选中的key
        setkey = 'selected_cart_%userid'%userid
        selectedlist = conn.smembers(setkey)
        #封装页面所需要的数据
        if cart:
            for k,v in cart.items():
                total+=int(v)
                #去goods表中查,k=goodsid
                goods = Goods.objects.filter(id=k).first()
                
                #封装产品列表
                gdict={}
                gdict['id']=goods.id
                gdict['name']=goods.name
                gdict['price']=goods.price
                gdict['pic']=MEDIA_URL+str(goods.pic)
                gdict['count']=v
                if k in selectedlist:
                    #选中价格
                    selectedtmoney+=int(v)*goods.price
                    #选中数量
                    selectedtcount+=int(v)
                    gdict['selected']=True
                    slist.append(gdict)
                else:
                    gdict['selected']=False
                    selectedall = False

                cartlist.append(gdict)
        #返回
        return Response({"code":200,'total':total,'cartlist':cartlist,'selectedtmoney':selectedtmoney,'selectedtcount':selectedtcount,'selectedall':selectedall,'slist':slist})

    def put(self,request):
        #'userid':userid,'goodsid':id,'type':type
        userid = int(request.data.get('userid'))
        goodsid = int(request.data.get('goodsid'))
        type = int(request.data.get('type'))
        #构造购物车key
        key = 'cart_%userid'%int(userid)
        #判断type 1加 2减
        conn = get_redis_conn()
        if type == 1:
            conn.hincrby(key,goodsid,1)
        elif type == 2:
            #减的时候判断
            count = conn.hget(key,goodsid)
            if int(count) >1:
                conn.hincrby(key,goodsid,-1)
            else:
                return Response({'code':20010})
        elif type == 3:
            number = request.data.get('number')
            if int(number) >= 1:
                conn.hset(key,goodsid,number)
            else:
                return Response({'code':20010})
        return Response({'code':200})
        
        


class ModifyCart(APIView):
    def post(self,request):
        #获取全选状态
        selectedall = request.data.get('selectedall') 
        userid = int(request.data.get('userid'))
        #获取redis conn
        conn = get_redis_conn()
        key = 'cart_%userid'%int(userid)
        carts = conn.hgetall(key)
        #选中的key
        setkey = 'selected_cart_%userid'%userid
        #全选，购物车里面id加到选中列表
        if selectedall:
            #定义一个选中的set
            conn.sadd(setkey,*carts.keys())
        else:
            #反选,选中列表清空
            conn.srem(setkey,*carts.keys())
        print(conn.smembers(setkey))
        return Response({'code':200})

    def put(self,request):
        #{'userid':userid,'goods_id':goods_id,'selected':status}
        #获取用户传递的参数
        userid = int(request.data.get('userid'))
        goods_id = request.data.get('goods_id')
        selected = request.data.get('selected')
        setkey = 'selected_cart_%userid'%userid
        #获取redis
        conn = get_redis_conn()
        if selected:
            conn.sadd(setkey,goods_id)
        else:
            conn.srem(setkey,goods_id)
        return Response({'code':200})

#获取用户地址列表
class AddressManage(APIView):
    def get(self,request):
        user_id = request.GET.get('user_id')
        id = request.GET.get('id')
        if id:
            address = Address.objects.filter(id=id).first()
            ser = AddressSer(address)
        else:
            #根据user_id查询地址
            address = Address.objects.filter(user_id=user_id).all()
            ser = AddressSer(address,many=True)
        return Response({"code":200,'addresslist':ser.data})

    def post(self,request):
        #判断是添加还是修改
        id = request.data.get('id')
        if id:
            #修改
            address = Address.objects.filter(id=id).first()
            ser = AddressSer(address,request.data)
        else:
            #添加
             ser = AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code':200})
        else:
            print(ser.errors)
            return Response({'code':40010})

#省市区管理
class AreaManage(APIView):
    def get(self,request):
        parent_id = request.GET.get('parent_id')
        if parent_id:
            area = Area.objects.filter(id=parent_id).first()
            area = area.son
        else:
            area = Area.objects.filter(parent__isnull=True).all()
        ser = AreaSer(area,many=True)
        return Response({"code":200,'area':ser.data})

#我最近浏览,详情页调用
class History(APIView):
    def post(self,request):
        goods_id = request.data.get('goods_id')
        user_id = request.data.get('user_id')
        #构造key
        key = 'history_%userid'%int(user_id)
        #去重
        conn = get_redis_conn()
        conn.lrem(key,0,goods_id)
        #添加
        conn.lpush(key,goods_id)
        #截取
        conn.ltrim(key,0,4)
        return Response("ok")
        
    def get(self,request):
        user_id = request.data.get('user_id')
        #构造key
        key = 'history_%userid'%int(user_id)
        #去重
        conn = get_redis_conn()
        ids = conn.lrange(key,0,-1)
        list=[]
        for i in ids:
            good = Goods.objects.filter(id=i).first()
            ser = GoodsSer(good)
            list.append(ser.data)
        return Response({"ids":list})

from datetime import datetime
import random
from django.db import transaction
#生成订单
class OrderManage(APIView):

    @transaction.atomic
    def post(self,request):
        #获取三个参数
        user_id = request.data.get('user_id')
        pay_type = request.data.get('pay_type')
        address_id = request.data.get('address_id')
       
        #查询购物车
        conn = get_redis_conn()
        #购物车key
        key = 'cart_%userid'%int(user_id)
        #选中
        setkey = 'selected_cart_%userid'%int(user_id)
        #获取购物车的信息
        carts = conn.hgetall(key)
        #获取选中的购物车列表
        selectedlist = conn.smembers(setkey)
        #总价
        total_amount=0
        for k,v in carts.items():
            if k in selectedlist:
                goods = Goods.objects.filter(id=k).first()
                total_amount += int(v)*goods.price


        #构造订单数据 订单号 年月日时分秒+4位随机数+userid
        time = datetime.strftime(datetime.now(),'%Y%m%s%H%M%S')  
        order_no = str(time)+str(user_id)+str(random.randint(1000,9999))
        #新建一个事务结点
        sid = transaction.savepoint()
        try:
            #生成订单
            OrderInfo.objects.create(order_no=order_no,user_id=user_id,address=address_id,pay_method=pay_type,status=1,transaction_no='',total_amount=total_amount)

            #构造订单详情,更新销量
            for k,v in carts.items():
                if k in selectedlist:
                    goods = Goods.objects.select_for_update().filter(id=k).first()
                    #判断库存
                    if int(v)>goods.store:
                        transaction.savepoint_rollback(sid)
                        return Response({"code":40020,'mes':goods.name+'库存不足'})

                    #生成订单详情
                    OrderDetail.objects.create(order_id=order_no,goods_id=goods.id,goodsname=goods.name,images=goods.pic,count=v,price=goods.price,user_id=user_id)
                    #redis删除商品
                    # conn.hdel(key,k)

                    # #更新销量
                    # goods.sales += int(v)
                    # goods.save()
            transaction.savepoint_commit(sid)
            return Response({"code":200,'order_no':order_no,'tmoney':total_amount})
        except:
            transaction.savepoint_rollback(sid)
            return Response({"code":40010})
    
    def get(self,request):
        #获取userid
        userid = request.GET.get('userid')
        #根据userid获取所有订单
        orderinfo = OrderInfo.objects.filter(user_id=userid).all().order_by('-create_time')
        ser = OrdersSer(orderinfo,many=True)
        #返回结果
        return Response({"orderlist":ser.data})
#支付
class Pay(APIView):
    def get(self,request):
        order_no = request.GET.get('order_no')
        order = OrderInfo.objects.filter(order_no=order_no).first()
        if order:
            alipay = get_ali_object()

            # 生成支付的url
            query_params = alipay.direct_pay(
                subject="美多订单支付",  # 商品简单描述
                out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样）
                total_amount=float(order.total_amount),  # 交易金额(单位: 元 保留俩位小数)
            )
            pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
            
            return Response({'code':200,'url':pay_url})
        else:
            return Response({"code":40020,'mes':'没有此订单不能支付'})

#支付宝回调
class Notify(APIView):
    @transaction.atomic
    def get(self,request):
        #订单号
        out_trade_no = request.GET.get('out_trade_no')
        #支付宝的流水号
        trade_no = request.GET.get('trade_no')
        #根据订单号查询订单
        orderinfo = OrderInfo.objects.filter(order_no=out_trade_no).first()
        sid = transaction.savepoint()
        try:
            if orderinfo and orderinfo.status == 1:
                #订单的支付状态，是1
                #支付成功后，更新订单状态
                orderinfo.status=2
                orderinfo.transaction_no = trade_no
                orderinfo.save()
                #查询订单详情，更新库存和销量
                # print(orderinfo.details)
                details = orderinfo.details.all()
                for i in details:
                    goods = Goods.objects.filter(id=i.goods_id).first()
                    goods.sales += i.count
                    goods.store -= i.count
                    goods.save()
            transaction.savepoint_commit(sid)
            return Response({'code':200})
        except:
            transaction.savepoint_rollback(sid)
            return Response({'code':40020})

        
class CommentMange(APIView):
    def post(self,request):
        ser  = CommentSer(data=request.data)
        if ser.is_valid():
            ser.save()
            #更新商品表中的总评论数
            goods = Goods.objects.filter(id=request.data.get('goods')).first()
            goods.comments+=1
            goods.save()
            return Response({'code':200})
        else:
            print(ser.errors)
            return Response({'code':40010})

#获取商品信息
class GoodsManage(APIView):
    def get(self,request):
        id = request.GET.get('id')
        userid = request.GET.get('userid')
        goods = Goods.objects.filter(id=id).first()
        ser = GoodsSer(goods)
        flag = 1
        #判断是否被收藏
        ids = goods.users.all().values('id')
        for i in ids:
            if int(userid) == int(i['id']):
                flag=2
        return Response({'good':ser.data,'flag':flag})

#收藏
class Collect(APIView):
    def post(self,request):
        #获取用户id和商品id
        userid = request.data.get('userid')
        g_id = request.data.get('g_id')
        type = request.data.get('type')
        #根据id获取对象
        user = Users.objects.filter(id=userid).first()
        goods = Goods.objects.filter(id=g_id).first()
        #添加
        if type == 1:
            goods.users.add(user)
        elif type == 2:
            goods.users.remove(user)
        return Response("ok")


class Weibo(APIView):
    def get(self,request):
         #回调网址
        redirect_url = "http://127.0.0.1:8000/users/weiboCallback/"
        #应用id
        client_id = "3648830690"

        url = "https://api.weibo.com/oauth2/authorize?client_id={client_id}&response_type=code&redirect_uri={redirect_url}".format(client_id=client_id,redirect_url=redirect_url)

        return Response({"code":200,'url':url})
            
import requests
class WeiboCallback(APIView):
    def get(self,request):
         #获取回调的code
        code = request.GET.get('code')
        #微博认证地址
        access_token_url = "https://api.weibo.com/oauth2/access_token"
        #参数
        response = requests.post(access_token_url,data={
            "client_id": '3648830690',
            "client_secret": "916d80b477ccffce5d70e63b02bb1092",
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "http://127.0.0.1:8000/users/weiboCallback/",
        })
        res = response.text
        res = eval(str(res))
        #获取用户id,token
        uid = res.get('uid')
        token = res.get('access_token')
        id = ''
        username=''
        #先查询是否已经登录过，如果登录过，获取用户信息
        sflogin = SFLogin.objects.filter(uid=uid).first()
        if sflogin:
            ser = SFLoginSer(sflogin)
            sflogin = ser.data
            id = sflogin['userid']['id']
            username = sflogin['userid']['username']
    
        return redirect('http://localhost:8080/#/bindAccount?uid='+uid+'&token='+token+'&id='+str(id)+'&username='+username)

from django.db.models import Q   
        
class Bind(APIView):
    def post(self,request):
        #获取uid,token,username
        uid = request.data.get('uid')
        token = request.data.get('token')
        username = request.data.get('username')
        #根据用户名先去用户表中查，如果有绑定已经存在的用户
        users = Users.objects.filter(Q(username=username)|Q(mobile=username)).first()
        if users:
            SFLogin.objects.create(userid_id=users.id,uid=uid,token=token)
        #如果没有创建用户，绑定
        else:
            user_id = Users.objects.create(username=username)
            SFLogin.objects.create(userid_id=user_id,uid=uid,token=token)
            users = Users.objects.filter(id=user_id).first()

        ser = UserSer(users)
        return Response({"code":200,'users':ser.data})

        


# from drf_haystack.viewsets import HaystackViewSet
# from rest_framework.viewsets import ModelViewSet

# class ESTESTView(HaystackViewSet):
    
#     """
#     SKU搜索
#     """
#     index_models = [ESTEST]
    

#     serializer_class = ESTESTIndexSerializer 
       
from drf_haystack.viewsets import HaystackViewSet

class BookSearchView(HaystackViewSet):
    index_models = [Book]

    serializer_class = BookIndexSerializer